package com.contactmanager;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Sync {

	public void update(String username, long updateTime,
			ArrayList<Contact> contacts, ArrayList<Group> groups,
			ContactsDataSource cds, String gUser) {
		/*
		 * ConnectivityManager connMgr; NetworkInfo networkInfo; connMgr =
		 * (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 * networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null
		 * && networkInfo.isConnected()) {
		 */
		JSONObject info = getJSON(username);// fetch data
		long cloudStamp = -1;
		try {
			if (info.has("tstamp")) {
				cloudStamp = info.getLong("tstamp");
			} else {

				Calendar cal = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String stamp = info.getString("timestamp");
				Date date;
				try {
					date = sdf.parse(stamp);
					cloudStamp = date.getTime();
				} catch (java.text.ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// check time stamps
		long localStamp = updateTime;
		if (gUser.equals("")) {
			pull(username, cds);
			return;
		}
		if (!gUser.equals(username))
			localStamp = -2;
		if (localStamp == cloudStamp)
			return;
		if (localStamp > cloudStamp) {
			// update cloud and keep local the same
			push(username, updateTime, contacts, groups, cds);
		} else {
			// update local and keep cloud the same
			pull(username, cds);
		}
		/*
		 * } else { // display error }
		 */
	}

	public JSONObject getJSON(String username) {
		JSONObject jObj = null;
		String json = "";
		String url = "http://softeng.cs.uwosh.edu/students/kempk79/functions.php";
		// Making HTTP request
		try {
			HttpPost httpPost = new HttpPost(url);
			HttpClient httpClient = new DefaultHttpClient();
			ArrayList<NameValuePair> postParameters;

			postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("username", username));
			postParameters.add(new BasicNameValuePair("get_update", "true"));

			httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

			HttpResponse httpResponse = httpClient.execute(httpPost);

			HttpEntity httpEntity = httpResponse.getEntity();
			json = EntityUtils.toString(httpEntity);
		} catch (IOException e) {
			System.out.println(e);
		}
		if (json.equals("")) {
			jObj = new JSONObject();
			return jObj;
		} else {
			try {
				jObj = new JSONObject(json);
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}

			// return JSON String
			return jObj;
		}
	}

	public void push(String username, long updateTime,
			ArrayList<Contact> contacts, ArrayList<Group> groups,
			ContactsDataSource cds) {
		System.out.println("Pushing info");
		/*
		 * ConnectivityManager connMgr = (ConnectivityManager)
		 * getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo
		 * networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null
		 * && networkInfo.isConnected()) {
		 */try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("tstamp", updateTime);
			JSONArray cont = new JSONArray();
			for (int i = 0; i < contacts.size(); i++) {// get all
				JSONArray jsonArray = new JSONArray();
				Contact c = contacts.get(i);
				long id = c.getId();
				String name = c.getName();
				String address = c.getAddress();
				String cell = c.getCell();
				String email = c.getEmail();
				String alt = c.getAlt();
				String comments = c.getComments();
				int group = c.getGroup();
				jsonArray.put(id);
				jsonArray.put(name);
				jsonArray.put(address);
				jsonArray.put(cell);
				jsonArray.put(alt);
				jsonArray.put(email);
				jsonArray.put(comments);
				jsonArray.put(group);
				System.out.println(id);
				System.out.println(name);
				System.out.println(address);
				System.out.println(cell);
				System.out.println(alt);
				System.out.println(email);
				System.out.println(comments);
				System.out.println(group);
				Log.d("CM", "ID: " + id + " NAME: " + name);
				jsonObject.put("contact" + i, jsonArray);
				System.out.println(jsonArray.toString());
			}
			// get all group info
			for (int i = 0; i < groups.size(); i++) {
				JSONArray jsonArray = new JSONArray();
				Group a = groups.get(i);
				long id = a.getGroupId();
				jsonArray.put(id);
				String name = a.getGroupName();
				jsonArray.put(name);
				Log.d("CM", "ID: " + id + " NAME: " + name);
				jsonObject.put("group" + i, jsonArray);
				System.out.println(jsonArray.toString());
			}
			/*
			 * update=true& username=[username]& json=[json_string]
			 */
			String str = "";
			String url = "http://softeng.cs.uwosh.edu/students/kempk79/functions.php";
			// Making HTTP request
			try {
				HttpPost httpPost = new HttpPost(url);
				HttpClient httpClient = new DefaultHttpClient();
				ArrayList<NameValuePair> postParameters;

				postParameters = new ArrayList<NameValuePair>();
				postParameters
						.add(new BasicNameValuePair("username", username));
				postParameters.add(new BasicNameValuePair("update", "true"));
				System.out.println(jsonObject.toString());
				postParameters.add(new BasicNameValuePair("json", jsonObject
						.toString()));
				httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

				HttpResponse httpResponse = httpClient.execute(httpPost);

				HttpEntity httpEntity = httpResponse.getEntity();
				str = EntityUtils.toString(httpEntity);
			} catch (IOException e) {
				System.out.println(e);
			}
			System.out.println(str);
			// send update
		} catch (JSONException e) {
			e.printStackTrace();
		}
		// }
	}

	private void pull(String username, ContactsDataSource cds) {
		System.out.println("Pulling info");
		cds.removeAll();
		/*JSONObject cloud = getJSON(username);
		try {
			cloud = cloud.getJSONObject("json");
		} catch (JSONException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		for (int i = 0; cloud.has("contact" + i); i++) {
			JSONArray cont = null;
			try {
				cont = cloud.getJSONArray("contact" + i);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			long id = i;
			String name = "", address = "", cell = "", alt = "", email = "", comments = "";
			int group = -1;
			try {
				if (cont.isNull(0))
					id = cont.getLong(0);
				if (cont.isNull(0))
					name = cont.getString(1);
				if (cont.isNull(0))
					address = cont.getString(2);
				if (cont.isNull(0))
					cell = cont.getString(3);
				if (cont.isNull(0))
					alt = cont.getString(4);
				if (cont.isNull(0))
					email = cont.getString(5);
				if (cont.isNull(0))
					comments = cont.getString(6);
				if (cont.isNull(0))
					group = cont.getInt(7) + 1;
				Log.d("CM", "ID: " + id + " NAME: " + name);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Contact c = new Contact(id, name, address, cell, alt, email,
					comments, group);
			if(name!=null||!name.equals(""))
				cds.addContact(c);
		}
		for (int i = 0; cloud.has("group" + i); i++) {
			JSONArray cont = null;
			try {
				cont = cloud.getJSONArray("group" + i);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			long id = -1;
			String name = null;
			try {
				name = cont.getString(0);
				id = cont.getInt(1);
				Log.d("CM", "ID: " + id + " NAME: " + name);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
			/*
			 * Group g = new Group(id, name); try { cds.updateGroups(g); } catch
			 * (Exception e) { // TODO Auto-generated catch block
			 * e.printStackTrace(); }
			 */
		} 

	}